package com.example.kotlinlearn

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.kotlinlearn.chat.Msg
import com.example.kotlinlearn.chat.MsgAdapter

class ChatActivity : BaseActivity() {

    private val msgList = ArrayList<Msg>()
    private var adapter:MsgAdapter?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_chat)
        initMsg()
        val layoutManager = LinearLayoutManager(this)
        val recyclerView:RecyclerView = findViewById(R.id.chatRecyclerView)
        val sendMsg:Button = findViewById(R.id.chatButton)
        val edit:EditText = findViewById(R.id.chatEditText)
        recyclerView.layoutManager = layoutManager
        adapter = MsgAdapter(msgList)
        recyclerView.adapter  =adapter
        sendMsg.setOnClickListener {
            val content = edit.text.toString()
            if (content.isNotEmpty()){
                val msg = Msg(content,Msg.TYPE_SENT)
                msgList.add(msg)
                //刷新recyc中的显示
                adapter?.notifyItemInserted(msgList.size -1)
                //定位到最后一行
                recyclerView.scrollToPosition(msgList.size-1)
                edit.setText("")
            }
        }

    }
    private fun initMsg(){
        val msg1 = Msg("你好啊！",Msg.TYPE_RECEIVED)
        val msg2 = Msg("你jb谁啊",Msg.TYPE_SENT)
        val msg3 = Msg("不要管我是谁",Msg.TYPE_RECEIVED)
        val msg4 = Msg("那你滚吧",Msg.TYPE_SENT)
        val msg5 = Msg("cnm！",Msg.TYPE_RECEIVED)
        msgList.add(msg1)
        msgList.add(msg2)
        msgList.add(msg3)
        msgList.add(msg4)
        msgList.add(msg5)
    }
}